package ooad.nextgen.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;

import ooad.nextgen.domain.ItemId;
import ooad.nextgen.domain.Money;
import ooad.nextgen.domain.Register;
import ooad.nextgen.domain.Store;
import ooad.nextgen.gof.observer.PropertyListener;

public class SaleFrame extends JFrame implements ActionListener,PropertyListener{
	private Register register;
	private static final long serialVersionUID = 1L;
	private JToolBar jToolBar;
	private JMenuBar jMenuBar;
	private JMenu jSystemMenu,jVIPMenu,jPaymentMenu;
	private JMenuItem jItemExit,jItemVipCard,jItemCreditPayment;
	private JPanel jContentPane,jToolBarPane,jMainPane,jPayPane,jStatusPane;
	private JScrollPane jDataListPane;
	private JTable table;
	private JLabel jTotalLabel,jCustomerLabel,jPayableLabel,jPreTotalLabel,jPaidLabel,jBalanceLabel;
	private JTextField jItemIdTextField,jItemQuantityTextField,jCustomerTextField,jPayableTextField,jPreTotalTextField,jPaidTextField,jBalanceTextField,jTotalTextField;
	private JButton jEnterItemButton,jEndSaleButton,jStartButton,jPayButton;
	private Object[][] a;
	private List<TableModel> tableModels = new ArrayList<TableModel>();

	public SaleFrame() {
                Store store = new Store();
		register = store.getRegister();
		this.setSize(800, 600);
                this.setLocationRelativeTo(null);
		this.setJMenuBar(getJMenuBar());
		this.setContentPane(getJContentPane());
		this.setTitle("OOAD Sample:NextGenPOS");
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
        public static void main(String args[]){
            new SaleFrame();
        }

	public JMenuBar getJMenuBar() {
		jMenuBar = new JMenuBar();
		jSystemMenu = new JMenu("System");
		jVIPMenu = new JMenu("Vip");
		jPaymentMenu = new JMenu("Payment");
		jItemExit = new JMenuItem("Exit");
		jItemExit.addActionListener(this);	
		jItemVipCard = new JMenuItem("Vip Card");
		jItemVipCard.addActionListener(this);	
		jItemCreditPayment = new JMenuItem("Credit Payment");		
		jItemCreditPayment.addActionListener(this);		
		jSystemMenu.add(jItemExit);
		jVIPMenu.add(jItemVipCard);
		jPaymentMenu.add(jItemCreditPayment);
		jMenuBar.add(jSystemMenu);
		jMenuBar.add(jVIPMenu);
		jMenuBar.add(jPaymentMenu);
		return jMenuBar;
	}
	public JPanel getJContentPane() {
		jContentPane = new JPanel();
		jContentPane.setLayout(new BorderLayout());
		jContentPane.add(getJToolBarPane(), BorderLayout.NORTH); 
		jContentPane.add(getJMainPane(), BorderLayout.CENTER); 
		jContentPane.add(getJPayPane(), BorderLayout.WEST); 
		jContentPane.add(getJStatusPane(), BorderLayout.SOUTH);
		return jContentPane;
	}

	public JPanel getJToolBarPane() {
		if (jToolBarPane == null) {
			jToolBarPane = new JPanel();
		}		
		jToolBar = new JToolBar();
		jToolBar.setPreferredSize(new Dimension(600,40));
		jToolBar.setLayout(new GridLayout(1, 6));
		jItemIdTextField = new JTextField();
        jItemIdTextField.setFont(new Font("宋体",Font.PLAIN,20));
		jItemIdTextField.setEditable(false);
        jItemIdTextField.addActionListener(this);
		jItemQuantityTextField = new JTextField("1");
        jItemQuantityTextField.setFont(new Font("宋体",Font.PLAIN,20));
		jItemQuantityTextField.setEditable(false);
		jEnterItemButton = new JButton("EnterItem(F2)");
        jEnterItemButton.setMnemonic(java.awt.event.KeyEvent.VK_F2);
		jEnterItemButton.setEnabled(false);
		jEnterItemButton.addActionListener(this);
		jEndSaleButton = new JButton("EndSale(F3)");
        jEndSaleButton.setMnemonic(java.awt.event.KeyEvent.VK_F3);
		jEndSaleButton.setEnabled(false);
		jEndSaleButton.addActionListener(this);
		jToolBar.add(new JLabel("ItemId"));		
		jToolBar.add(jItemIdTextField);
		jToolBar.add(new JLabel("Quantity"));
		jToolBar.add(jItemQuantityTextField);
		jToolBar.add(jEnterItemButton);
		jToolBar.add(jEndSaleButton);
		jToolBarPane.add(jToolBar);
		return jToolBarPane;
	}

	public JPanel getJMainPane(){
		jMainPane = new JPanel();
		jMainPane.setLayout(new BorderLayout());
		jMainPane.add(getJDataListPane(),BorderLayout.CENTER);
		return jMainPane;
	}

	public JScrollPane getJDataListPane() {
		if(jDataListPane == null){
			jDataListPane = new JScrollPane();
		}
		jDataListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		jDataListPane.setViewportView(getJTable());
		jDataListPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		return jDataListPane;
	}

	public JTable getJTable(){
		Object title[] = { "ItemId", "Name", "Price", "Quantity" };
		int count = 25;
		a = new Object[count][4];
		int row = 0;
		Iterator<TableModel> iter = tableModels.iterator();		
		while (iter.hasNext()) {
			TableModel vo = (TableModel) iter.next();
			a[row][0] = vo.getId();
			a[row][1] = vo.getDesc();
			a[row][2] = vo.getPrice();
			a[row][3] = vo.getQuantity();
			row ++;
		}
		table = new JTable(a, title);		
		return table;
	}

	public JPanel getJPayPane() {
		if (jPayPane == null) {
			jPayPane = new JPanel();
			jPayPane.setPreferredSize(new Dimension(150,500));
			jPayPane.setLayout(new GridLayout(12, 1));
		}
		jCustomerLabel = new JLabel("顾客编号");
		jPreTotalLabel = new JLabel("总金额");
		jPayableLabel = new JLabel("折后总金额");
		jPaidLabel = new JLabel("付款");
		jBalanceLabel = new JLabel("找零");
		jCustomerTextField = new JTextField();
        jCustomerTextField.setEditable(false);
        jPreTotalTextField = new JTextField("0.00");
        jPreTotalTextField.setFont(new Font("宋体",Font.PLAIN,20));
        jPreTotalTextField.setEditable(false);
        jPayableTextField = new JTextField("0.00");
        jPayableTextField.setForeground(Color.RED);
        jPayableTextField.setFont(new Font("宋体",Font.PLAIN,20));
		jPayableTextField.setEditable(false);
		jPaidTextField = new JTextField("0.00");
        jPaidTextField.setFont(new Font("宋体",Font.PLAIN,20));
        jPaidTextField.setForeground(Color.BLUE);
		jPaidTextField.setEditable(false);
		jBalanceTextField = new JTextField("0.00");
        jBalanceTextField.setFont(new Font("宋体",Font.PLAIN,20));
        jBalanceTextField.setForeground(Color.GREEN);
		jBalanceTextField.setEditable(false);
		jStartButton = new JButton("MakeNewSale(F1)");
		jStartButton.addActionListener(this);
        jStartButton.setMnemonic(java.awt.event.KeyEvent.VK_F1);  //Alt+F1
		jPayButton = new JButton("MakePayment(F4)");
        jPayButton.setMnemonic(java.awt.event.KeyEvent.VK_F4);  //Alt+F1
		jPayButton.setEnabled(false);
		jPayButton.addActionListener(this);
		jPayPane.add(jStartButton);
		jPayPane.add(jCustomerLabel);
		jPayPane.add(jCustomerTextField);
		jPayPane.add(jPreTotalLabel);
		jPayPane.add(jPreTotalTextField);
		jPayPane.add(jPayableLabel);
		jPayPane.add(jPayableTextField);
		jPayPane.add(jPaidLabel);
		jPayPane.add(jPaidTextField);
		jPayPane.add(jBalanceLabel);
		jPayPane.add(jBalanceTextField);
		jPayPane.add(jPayButton);
		return jPayPane;
	}	

	public JPanel getJStatusPane() {
		if (jStatusPane == null) {
			jStatusPane = new JPanel();
		}	
		
		jTotalLabel = new JLabel("Total:");
		jTotalTextField = new JTextField("0.00");
        jTotalTextField.setColumns(10);
        jTotalTextField.setFont(new Font("宋体",Font.PLAIN,30));
		jTotalTextField.setEditable(false);
		jStatusPane.add(jTotalLabel);
		jStatusPane.add(jTotalTextField);
		return jStatusPane;
	}

	public void refresh() { 
		jMainPane.removeAll();
		jMainPane.add(getJDataListPane(),BorderLayout.CENTER); 
		this.validate();	
	}
	public void clearTextField(){
		jItemIdTextField.setText(null);
		jPreTotalTextField.setText("0.00");
		jPayableTextField.setText("0.00");
		jPaidTextField.setText("0.00");
		jBalanceTextField.setText("0.00");
		jTotalTextField.setText("0.00");
		jItemIdTextField.setEditable(true);
		jItemQuantityTextField.setEditable(true);
		jEnterItemButton.setEnabled(true);
		jEndSaleButton.setEnabled(true);
		jPaidTextField.setEditable(false);
		jPayButton.setEnabled(false);
		
	}	

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jItemExit) {
                    System.exit(0);			
		}
		else if(e.getSource() == jStartButton) {
                    this.makeNewSale();
		}
		else if(e.getSource() == jEnterItemButton) {
                    this.enterItem();
		}
		else if(e.getSource()==jEndSaleButton){
                    this.endSale();
		}
		else if(e.getSource()==jPayButton){
                    this.makePayment();
		}
		
         else if(e.getSource()==jItemIdTextField){
                    this.enterItem();
         }
	}
        public void makeNewSale(){
            register.makeNewSale();	
        	register.getCurrentSale().addPropertyListener(this);
            this.tableModels.clear();
            this.refresh();
            this.clearTextField();
            jStartButton.setEnabled(false);
        }
        public void enterItem(){
            String str = jItemIdTextField.getText();
            int id = Integer.parseInt(str);
            int quantity = Integer.parseInt(jItemQuantityTextField.getText());
            ItemId itemId = register.getCatalog().getItemId(id);
            String description = register.getCatalog().getProductDescription(itemId).getDescription();
            double price = register.getCatalog().getProductDescription(itemId).getPrice().getAmount();
            register.enterItem(itemId, quantity);
            TableModel vo = new TableModel(id,description,price,quantity);
            this.tableModels.add(vo);
            this.refresh();	
        }
        public void endSale(){
            register.endSale();	
        	jPayableTextField.setText(Float.toString(register.getCurrentSale().getDiscountTotal().getAmount()));
            jPaidTextField.setEditable(true);
            jPayButton.setEnabled(true);
        }
        public void makePayment(){
            float amount = Float.parseFloat(jPaidTextField.getText());
            float total = Float.parseFloat(jPayableTextField.getText());
            register.makePayment(new Money(amount));
            jBalanceTextField.setText(Double.toString(amount-total));
            jPayButton.setEnabled(false);
            jStartButton.setEnabled(true);
        }

		@Override
		public void onPropertyEvent(Object source, String name, Object value) {
			if("sale.total".equals(name)){
	            jPreTotalTextField.setText(value.toString());
				jTotalTextField.setText(value.toString());
			}
		}
}

